package com.zk.code.net;

/**
 * Created by zhoukaich on 2018/8/9.
 */

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GenericFutureListener;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.List;

public class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        String response = msg.content().toString(CharsetUtil.UTF_8);
        /*ctx.writeAndFlush(new DatagramPacket(
                Unpooled.copiedBuffer("hello!!!", CharsetUtil.UTF_8),
                msg.sender()));*/

        System.out.println(response);
        ctx.close();

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        ctx.close();
    }

    /**
     * 向服务器发送消息
     *
     * @param msg               按规则拼接的消息串
     * @param inetSocketAddress 目标服务器地址
     */
    public static void sendMessage(final String msg, final InetSocketAddress inetSocketAddress) {
        if (msg == null) {
            throw new NullPointerException("msg is null");
        }
        // TODO 这一块的msg需要做处理 字符集转换和Bytebuf缓冲区
        senderInternal(datagramPacket(msg, inetSocketAddress));
    }

    /**
     * 发送数据包并监听结果
     *
     * @param datagramPacket
     */
    public static void senderInternal(final DatagramPacket datagramPacket, List<Channel> channelList) {
        for (Channel channel : channelList) {
            if (channel != null) {
                channel.writeAndFlush(datagramPacket).addListener(new GenericFutureListener<ChannelFuture>() {
                    public void operationComplete(ChannelFuture future)
                            throws Exception {
                        boolean success = future.isSuccess();

                        System.err.println("Sender datagramPacket result : " + success);

                    }
                });
            }
        }
    }

    public static void sendMess(final DatagramPacket datagramPacket, Channel channel) {
        try {
            channel.writeAndFlush(datagramPacket).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 组装数据包
     *
     * @param msg               消息串
     * @param inetSocketAddress 服务器地址
     * @return DatagramPacket
     */
    private static DatagramPacket datagramPacket(String msg, InetSocketAddress inetSocketAddress) {
        ByteBuf dataBuf = Unpooled.copiedBuffer(msg, Charset.forName("UTF-8"));
        DatagramPacket datagramPacket = new DatagramPacket(dataBuf, inetSocketAddress);
        return datagramPacket;
    }

    /**
     * 发送数据包服务器无返回结果
     *
     * @param datagramPacket
     */
    private static void senderInternal(final DatagramPacket datagramPacket) {
        System.err.println("LogPushUdpClient.channel" + UdpClient.channel);
        if (UdpClient.channel != null) {
            UdpClient.channel.writeAndFlush(datagramPacket).addListener(new GenericFutureListener<ChannelFuture>() {
                public void operationComplete(ChannelFuture future)
                        throws Exception {
                    boolean success = future.isSuccess();

                    System.err.println("Sender datagramPacket result : " + success);

                }
            });
        } else {
            throw new NullPointerException("channel is null");
        }
    }
}